#include <SoftwareSerial.h>
#include <TinyGPS.h>
#include <avr/sleep.h>

/* This sample code demonstrates the normal use of a TinyGPS object.
 It requires the use of SoftwareSerial, and assumes that you have a
 4800-baud serial GPS device hooked up on pins 3(rx) and 4(tx).
 */
#include <SdFat.h>
SdFat sd;
SdFile myFile;
const int chipSelect = 4;
TinyGPS gps;
SoftwareSerial ss(6, 7);
char time[32];
int lastupdatefix=0;
int year;
byte month, day, hour, minutes, second, hundredths;
char FileName[13];
int thisTXT;

int wakePin = 3;                 // pin used for waking up

int sleepStatus = 0;             // variable to store a request for sleep
int count = 0;                   // counter

void wakeUpNow()        // here the interrupt is handled after wakeup
{
  // execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  // we don't really need to execute any special functions here, since we
  // just want the thing to wake up
}

void fix(){

  lastupdatefix = millis();
}


int adjustDst()
{
  // last sunday of march
  int beginDSTDate=  (31 - (5* year /4 + 4) % 7);
  //  Serial.println(beginDSTDate);
  int beginDSTMonth=3;
  //last sunday of october
  int endDSTDate= (31 - (5 * year /4 + 1) % 7);
  //  Serial.println(endDSTDate);
  int endDSTMonth=10;
  // DST is valid as:
  if (((month > beginDSTMonth) && (month < endDSTMonth))
    || ((month == beginDSTMonth) && (day >= beginDSTDate)) 
    || ((month == endDSTMonth) && (day <= endDSTDate)))
    return 1;  // DST europe = utc +2 hour
  else return 0; // nonDST europe = utc +1 hour
}

void setup()
{
  pinMode(wakePin, INPUT);
  attachInterrupt(1, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
  randomSeed(analogRead(0));
  thisTXT = random(120);  // DO NOT go over 100 without adjusting the size of the buffer
  sprintf( FileName, "gpslog%i.txt", thisTXT );

  pinMode(8,OUTPUT);
  pinMode(A1,INPUT);
  pinMode(A2,INPUT);
  Serial.println("Loading");
  digitalWrite(8,HIGH);
  attachInterrupt(0, fix, CHANGE);
  Serial.begin(115200);
  ss.begin(4800);
  if (!sd.init(SPI_HALF_SPEED, chipSelect)) sd.initErrorHalt();

  // open the file for write at end like the Native SD library
  if (!myFile.open(FileName, O_RDWR | O_CREAT | O_AT_END)) {
    sd.errorHalt("opening File for write failed");
  }
  // if the file opened okay, write to it:
  Serial.print("Writing to ");
  Serial.println(FileName);
  myFile.println("Loading...");
  myFile.println("Welcome to Malyon GPS Tracking Log...");
  myFile.println("Lat,Lon,Sats,Prec,Alt,Course,Speed,Time,Millis,Cell1V,Cell2V");
  myFile.close();
  Serial.println("done.");

  // re-open the file for reading:
  if (!myFile.open(FileName, O_READ)) {
    sd.errorHalt("opening File for read failed");
  }
  Serial.print("Reading ");
  Serial.println(FileName);
  // read from the file until there's nothing else in it:
  int data;
  while ((data = myFile.read()) > 0) Serial.write(data);
  // close the file:
  myFile.close();
  digitalWrite(8,LOW);
}

void loop()
{
  if( millis() - lastupdatefix > 4000){
    Serial.println("GPS FIX"); 
  }

  unsigned long Cell1V;
  unsigned long Cell2V;
  Cell1V = analogRead(A1);
  Cell2V = analogRead(A2);
  bool newData = false;
  unsigned long chars;
  unsigned short sentences, failed;
  unsigned long age;
  // For one second we parse GPS data and report some key values
  for (unsigned long start = millis(); millis() - start < 1000;)
  {
    while (ss.available())
    {
      char c = ss.read();
      // Serial.write(c); // uncomment this line if you want to see the GPS data flowing
      if (gps.encode(c)) // Did a new valid sentence come in?
        newData = true;
    }
  }

  if (newData)
  {
    digitalWrite(8,HIGH);
    float flat, flon;
    unsigned long age;
    gps.f_get_position(&flat, &flon, &age);
    unsigned long fix_age, time1, date, speed, course;

    float falt = gps.f_altitude(); // +/- altitude in meters
    float fc = gps.f_course(); // course in degrees
    float fk = gps.f_speed_knots(); // speed in knots
    float fmph = gps.f_speed_mph(); // speed in miles/hr


    gps.crack_datetime(&year, &month, &day, &hour, &minutes, &second, &hundredths, &fix_age);

    sprintf(time, "%02d/%02d/%02d %02d:%02d:%02d", day, month, year, hour + adjustDst(), minutes, second);
    Serial.println(time);

    Serial.print("LAT=");
    Serial.print(flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : flat, 6);
    Serial.print(" LON=");
    Serial.print(flon == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : flon, 6);
    Serial.print(" SAT=");
    Serial.print(gps.satellites() == TinyGPS::GPS_INVALID_SATELLITES ? 0 : gps.satellites());
    Serial.print(" PREC=");
    Serial.print(gps.hdop() == TinyGPS::GPS_INVALID_HDOP ? 0 : gps.hdop());
    Serial.print(" Alt=");
    Serial.print(falt);
    Serial.print(" COURSE=");
    Serial.print(fc);
    Serial.print(" MPH=");
    Serial.print(fmph);    
    Serial.print(" TIME=");
    Serial.println(time);
    Serial.print("Writing to ");
    Serial.println(FileName);
    if (!myFile.open(FileName, O_RDWR | O_CREAT | O_AT_END)) {
      sd.errorHalt("opening File for write failed");
    }

    myFile.print(flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : flat, 6);
    myFile.print(",");
    myFile.print(flon == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : flon, 6);
    myFile.print(",");
    myFile.print(gps.satellites() == TinyGPS::GPS_INVALID_SATELLITES ? 0 : gps.satellites());
    myFile.print(",");
    myFile.print(gps.hdop() == TinyGPS::GPS_INVALID_HDOP ? 0 : gps.hdop());
    myFile.print(",");
    myFile.print(falt);
    myFile.print(",");
    myFile.print(fc);
    myFile.print(",");
    myFile.print(fmph);    
    myFile.print(",");
    myFile.print(time);
    myFile.print(",");
    myFile.print(millis());
    myFile.close();
    Serial.println("done.");
  } 
  else{
    if (!myFile.open(FileName, O_RDWR | O_CREAT | O_AT_END)) {
      sd.errorHalt("opening File for write failed");
    }
    //  sprintf(time, "%02d/%02d/%02d %02d:%02d:%02d", day(), month(), year(), hour(), minute(), second());
    myFile.print(" Uptime=");
    myFile.println(millis());
    myFile.close();
  }

  if (!myFile.open(FileName, O_RDWR | O_CREAT | O_AT_END)) {
    sd.errorHalt("opening File for write failed");
  }
  //  sprintf(time, "%02d/%02d/%02d %02d:%02d:%02d", day(), month(), year(), hour(), minute(), second());
  myFile.print(",");
  myFile.print(Cell1V);
  myFile.print(",");
  myFile.println(Cell2V);
  myFile.close();

  gps.stats(&chars, &sentences, &failed);
  Serial.print(" CHARS=");
  Serial.print(chars);
  Serial.print(" SENTENCES=");
  Serial.print(sentences);
  Serial.print(" CSUM ERR=");
  Serial.print(failed);
  Serial.print(" Uptime=");
  Serial.println(millis());
  Serial.print(" CELL1V=");
  Serial.print(Cell1V);
  Serial.print(" CELL2V=");
  Serial.println(Cell2V);
  digitalWrite(8,LOW);
  
  if(Cell1V < 450 || Cell2V < 450){
   sleepNow();     // sleep function called here 
  }
}



void sleepNow()         // here we put the arduino to sleep
{
   /*
     * The 5 different modes are:
     *     SLEEP_MODE_IDLE         -the least power savings 
     *     SLEEP_MODE_ADC
     *     SLEEP_MODE_PWR_SAVE
     *     SLEEP_MODE_STANDBY
     *     SLEEP_MODE_PWR_DOWN     -the most power savings
     *
     * For now, we want as much power savings as possible, so we 
     * choose the according 
     * sleep mode: SLEEP_MODE_PWR_DOWN
     * 
     */  
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here

    sleep_enable();          // enables the sleep bit in the mcucr register
                             // so sleep is possible. just a safety pin 

    attachInterrupt(0,wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
                                       // wakeUpNow when pin 2 gets LOW 

    sleep_mode();            // here the device is actually put to sleep!!
                             // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP

    sleep_disable();         // first thing after waking from sleep:
                             // disable sleep...
    detachInterrupt(0);      // disables interrupt 0 on pin 2 so the 
                             // wakeUpNow code will not be executed 
                             // during normal running time.

}



